package main

import (
	"fmt"
	"os"

	"../pb"

	"github.com/op/go-logging"
	"google.golang.org/grpc"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	path     = kingpin.Flag("path", "store path").Short('s').Required().String()
	port     = kingpin.Flag("port", "listen port").Short('p').Required().String()
	log_file = kingpin.Flag("log", "log file.").Short('l').String()
	log      = logging.MustGetLogger("client")
)

func main() {
	kingpin.Parse()
	if *log_file == "" {
		bk := logging.NewLogBackend(os.Stderr, "", 0)
		logging.SetBackend(bk)
	} else {
		file, err := os.OpenFile(*log_file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
		if err != nil {
			log.Errorf("open log file %s , error: ", *log_file, err)
		}
		defer file.Close()
		bk := logging.NewLogBackend(file, "", 0)
		logging.SetBackend(bk)
	}

	fmt.Println("===================================================================================")
	var host string
	fmt.Println("#please input host:")
	fmt.Scanln(&host)
	if host == "exit" {
		os.Exit(0)
	}
	var name string
	fmt.Println("#please input name:")
	fmt.Scanln(&name)
	if name == "exit" {
		os.Exit(0)
	}
	conn, err := grpc.Dial(fmt.Sprintf("%s%s", host, *port), grpc.WithInsecure())
	if err != nil {
		log.Error(err)
		os.Exit(2)
	}
	defer conn.Close()
	cli := pb.NewFileServiceClient(conn)

	fc := &flieClient{name: name, basePath: *path, cli: cli, Files: make(map[string]*os.File)}
	err = fc.GetFiles()
	if err != nil {
		log.Error(err)
		os.Exit(2)
	}
	log.Info("success!!")
}
